package cn.texous.easytalk.manager.controller;

import cn.texous.easytalk.commonutil.constant.RedisKey;
import cn.texous.easytalk.commonutil.constant.ResultCode;
import cn.texous.easytalk.commonutil.exception.BusinessException;
import cn.texous.easytalk.commonutil.util.GsonUtils;
import cn.texous.easytalk.commonutil.util.RedisKeyUtil;
import cn.texous.easytalk.manager.model.dto.UserDto;
import cn.texous.starter.redis.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/8/30 17:03
 */
@Slf4j
public class BaseController {

    /**
     * 获取当前request
     *
     * @return
     */
    public HttpServletRequest request() {
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 获取 access token
     * @return
     */
    public String getToken() {
        return request().getHeader("access_token");
    }

    /**
     * 获取 access token
     * 如果为 null 则抛出异常
     * @return
     */
    public String getTokenNotNull() {
        return Optional.ofNullable(getToken())
                .orElseThrow(() -> new BusinessException(ResultCode.USER_UNLOGIN_ERROR));
    }

    /**
     * 获取但钱用户信息
     * @return
     */
    public UserDto currentUser() {
        String key = RedisKeyUtil.getKey(RedisKey.USER_LOGIN_TOKEN, getToken());
        String userInfo = RedisClient.get(key);
        return Optional.ofNullable(userInfo)
                .map(u -> GsonUtils.fromJson(userInfo, UserDto.class))
                .orElse(null);
    }

    /**
     * 获取当前用户信息 部位空
     * @return
     */
    public UserDto currentUserNotNull() {
        String key = RedisKeyUtil.getKey(RedisKey.USER_LOGIN_TOKEN, getTokenNotNull());
        return Optional.ofNullable(key)
                .filter(RedisClient::exists)
                .map(RedisClient::get)
                .map(p -> GsonUtils.fromJson(p, UserDto.class))
                .orElseThrow(() -> new BusinessException(ResultCode.USER_UNLOGIN_ERROR));
    }

}
